<script>
import { mapGetters, mapState } from 'vuex'

export default {
  name: 'entForm',
  data() {
    return {
      /* 表单数据对象 */
      formData: {
        // 企业名称
        name: '',
        // 企业法人
        legalPerson: '',
        // 注册地址
        registeredAddress: '',
        // 行业编号
        industryCode: '',
        // 上传文件url
        businessLicenseUrl: '',
        // 上传文件id
        businessLicenseId: '',
        // 企业联系人
        contact: '',
        // 企业联系方式
        contactNumber: ''
      },
      fileList: [],
      /* 表单规则对象 */
      formRules: {
        name: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
        legalPerson: [{ required: true, message: '请输入法人代表', trigger: 'blur' }],
        industryCode: [{ required: true, message: '请选择所在行业', trigger: 'change' }],
        registeredAddress: [{ required: true, message: '请输入注册地址', trigger: 'blur' }],
        businessLicenseId: [{ required: true, message: '请上传营业执照' }],
        contact: [{ required: true, message: '请输入企业联系人', trigger: 'blur' }],
        contactNumber: [{ required: true, message: '请输入联系电话', trigger: 'blur' }]
      }
    }
  },
  methods: {
    /* 查询企业的回调函数 */
    async findEnterprise(enterpriseId) {
      try {
        const { name, id, legalPerson, registeredAddress, industryCode, businessLicenseUrl, businessLicenseName, businessLicenseId, contact, contactNumber } = await this.$store.dispatch('enterpriseStore/findEnterprise', enterpriseId)
        this.formData = { name, id, legalPerson, registeredAddress, industryCode, businessLicenseUrl, businessLicenseName, businessLicenseId, contact, contactNumber }
        this.fileList = [{ name: businessLicenseName, url: businessLicenseUrl }]
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    /* 获取行业列表的回调函数 */
    async fetchIndustryList() {
      try {
        await this.$store.dispatch('enterpriseStore/fetchIndustryList')
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    /* 添加企业的回调函数 */
    async doAddEnterprise(formData) {
      try {
        const addResult = await this.$store.dispatch('enterpriseStore/addEnterprise', formData)
        this.$message.success(addResult)
        this.$emit('success')
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    /* 编辑企业的回调函数 */
    async doEditEnterprise(formData) {
      try {
        const editResult = await this.$store.dispatch('enterpriseStore/editEnterprise', formData)
        this.$message.success(editResult)
        this.$emit('success')
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    /* 删除文件之前的钩子，参数为上传的文件和文件列表，若返回 false 或者返回 Promise 且被 reject，则停止删除 */
    handleRemove() {
      this.formData.businessLicenseUrl = ''
      this.formData.businessLicenseId = ''
      this.formData.businessLicenseName = ''
      this.$refs.formRef.validateField('businessLicenseId')
    },
    /* 件超出个数限制时的钩子 */
    handleExceed() {
      this.$message.error('只能上传一张图片')
    },
    /* 覆盖默认的上传行为，可以自定义上传的实现 */
    async handleRequest({ file }) {
      try {
        const formData = new FormData()
        formData.append('file', file)
        formData.append('type', '1')
        const { id, url } = await this.$store.dispatch('enterpriseStore/upload', formData)
        // 收集上传文件的URL地址和ID
        this.formData.businessLicenseId = id
        this.formData.businessLicenseUrl = url
        this.$message.success('营业执照上传成功')
        this.$refs.formRef.validateField('businessLicenseId')
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    /* 文件上传之前的回调函数 */
    beforeUpload(file) {
      const isImg = file.type.startsWith('image')
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isImg) {
        this.$message.error('只能上传图片!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过2MB!')
      }
      return isImg && isLt2M
    },
    /* 清空表单数据的回调函数 */
    resetFormData() {
      this.$refs.formRef.resetFields()
      this.formData.businessLicenseUrl = ''
      this.formData.businessLicenseName = ''
      this.formData.id = ''
      this.fileList = []
    },
    /* 点击确定按钮的回调函数 */
    async handleSubmit() {
      const valid = await this.$refs.formRef.validate().catch(error => error)
      if (!valid) return
      if (this.formData.id) {
        delete this.formData.businessLicenseName
        await this.doEditEnterprise(this.formData)
      } else {
        await this.doAddEnterprise(this.formData)
      }

    }
  },
  computed: {
    ...mapState('enterpriseStore', ['industryList'])
  },
  created() {
    this.fetchIndustryList()
  },
  emits: ['success']
}
</script>

<template>
  <el-form label-width="100px" :model="formData" :rules="formRules" ref="formRef">
    <el-form-item label="企业名称" prop="name">
      <el-input placeholder="请输入企业名称" size="small" v-model="formData.name"></el-input>
    </el-form-item>
    <el-form-item label="法人代表" prop="legalPerson">
      <el-input placeholder="请输入法人代表" size="small" v-model="formData.legalPerson"></el-input>
    </el-form-item>
    <el-form-item label="注册地址" prop="registeredAddress">
      <el-input placeholder="请输入注册地址" size="small" v-model="formData.registeredAddress"></el-input>
    </el-form-item>
    <el-form-item label="所在行业" prop="industryCode">
      <el-select placeholder="请选择所在行业" size="small" v-model="formData.industryCode">
        <el-option v-for="(item) in industryList" :value="item.industryCode" :label="item.industryName" :key="item.industryCode"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="企业联系人" prop="contact">
      <el-input placeholder="请输入企业联系人" size="small" v-model="formData.contact"></el-input>
    </el-form-item>
    <el-form-item label="联系电话" prop="contactNumber">
      <el-input placeholder="请输入企业联系人电话" size="small" v-model="formData.contactNumber"></el-input>
    </el-form-item>
    <el-form-item label="营业执照" prop="businessLicenseId">
      <el-upload action="#" :limit="1" :file-list="fileList" :on-remove="handleRemove" :on-exceed="handleExceed" :http-request="handleRequest" :before-upload="beforeUpload">
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传图片，且不超过2MB</div>
      </el-upload>
    </el-form-item>
    <el-form-item>
      <el-button size="small">取消</el-button>
      <el-button type="primary" size="small" @click="handleSubmit">确定</el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped lang="scss">
.el-form {
  .el-select {
    width: 100%;
  }
}
</style>
